import Utils from "./Util";

export class ScoreObjPool {
    public static scoreObjPool = null;
    public static initCount = null;

    public static InitPool() {
        this.scoreObjPool = new cc.NodePool();

        this.initCount = 5;

        for (let i = 0; i < this.initCount; ++i) {
            Utils.GetPrefab("prefab/ScoreNode", (prefab) => {
                var scoreNode = cc.instantiate(prefab);
                this.scoreObjPool.put(scoreNode); // 通过 putInPool 接口放入对象池
            }, this);
        }
    }

    public static async GetScoreObj() {
        let scoreObj = null;

        if (this.scoreObjPool) {
            // 通过 size 接口判断对象池中是否有空闲的对象
            if (this.scoreObjPool.size() > 0) {
                scoreObj = this.scoreObjPool.get();
                var scoreCom = Utils.GetComponent(scoreObj, "ScoreCom");
                if (scoreCom) {
                    scoreCom.init();
                }
            } else {
                return new Promise(resolve => {
                    // 如果没有空闲对象，也就是对象池中备用对象不够时，我们就用 cc.instantiate 重新创建
                   Utils.GetPrefab("prefab/ScoreNode", (prefab) => {
                        scoreObj = cc.instantiate(prefab);
                        var scoreCom = Utils.GetComponent(scoreObj, "ScoreCom");
                        if (scoreCom) {
                            scoreCom.init();
                            resolve();
                        }
                    }, this);
                })
            }
        }

        return scoreObj;
    }

    public static PutScoreObj(scoreObj) {
        if (this.scoreObjPool) {
            this.scoreObjPool.put(scoreObj);
        }
    }

    public static DestroyPool() {
        if (this.scoreObjPool) {
            this.scoreObjPool.clear();
        }
        this.scoreObjPool = null;
    }
}
